08 / 19

Why is string concatenation in a loop O(n²)? How do you fix it? (StringBuilder)

Efficient String Construction

javascript
  1. 1

    Immutable strings cannot be modified in place.

  2. 2

    Repeated concatenation may create many temporary objects.

  3. 3

    The cumulative copying can become quadratic for a growing result.

  4. 4

    StringBuilder maintains a mutable buffer and grows its capacity as needed.

  5. 5

    With suitable capacity management, StringBuilder typically provides near-linear total construction time.

Difficulty: 3/10

Follow-up Questions

  • What is the complexity of StringBuilder append?
  • When is simple string concatenation acceptable?